import java.net.*;
import java.io.*;

/*处理连接任务，并提供一些有用的函数
 */
public class Connection {
	public static final int CMD_USERINFO=1;
	public static final int CMD_SETID=2;
	public static final int CMD_JOIN=3;
	public static final int CMD_FULL=4;
	public static final int CMD_READY=5;
	public static final int CMD_DEALCARDS=6;
	public static final int CMD_SETLANDLORD=7;
	public static final int CMD_PLAY=8;
	public static final int CMD_WIN=9;
	public static final int CMD_AUCTION=10;
	public static final int CMD_ILLEGAL=11;
	public static final int CMD_TABLEINFO=12;
	public static final int CMD_PASS=13;
	Socket socket;
	BufferedReader in;
	PrintWriter out;
	
	public Connection(Socket socket) {
        this.socket = socket;
        try {
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
			out = new java.io.PrintWriter(this.socket.getOutputStream());
        }
        catch (IOException e) {
            try { this.socket.close(); } catch (IOException e2) { ; }
            e.printStackTrace();
            return;
        }
    }
    
    /*以字符串形式发送格式化后的信息
     */
    public  void sendMsg(String msg) {
		System.out.println(msg);
		try{
			out.println( msg );
			out.flush();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/*接收字符串形式的信息
	 */
    public  String receiveMsg() {
		String msg = new String();
		try {
			msg = in.readLine();
		} catch(IOException e) {
              e.printStackTrace();
		}
		System.out.println(msg);
		return msg;
	}
	
	/*从接收的字符串信息中，取出参数的值
	 *name是参数名，str是接收到的字符串
	 */
	public static String getValue(String name,String str){
		String[] values=str.split("&");
		for(int i=0;i<values.length;i++){
			String [] val=values[i].split("=");
			if (val[0].equalsIgnoreCase(name)) return val[1];
			}
		return null;
	}
	
	public static int getIntValue(String name,String str){
		try{
			return Integer.parseInt(getValue(name,str));
			}catch(Exception e){
				e.printStackTrace();
			}
		return -1;	
	}	
	
	public static int getCmd(String str){
		int i=CMD_ILLEGAL;
		try{
			i = Integer.parseInt(getValue("cmd",str));
		}catch(Exception e){e.printStackTrace();}
		return i;
	}
	/*从接收的字符串信息中，得到所出的牌
	 *str是接收到的字符串
	 */	
	public static int[] getCards(String str){
		String cardStr=getValue("cards",str);
		String [] ss=cardStr.split(",");
		int [] cardsValue=new int[ss.length];
		for(int i=0;i<ss.length;i++){
			try{
			cardsValue[i]=Integer.parseInt(ss[i]);
			}catch(Exception e){e.printStackTrace();}
		}
		return cardsValue;
	}
	
}